<template>
	<div class="order">
		<el-row class="searchForm" v-if="showSearch">
			<el-col>
				<el-form
					ref="searchForm"
					:model="searchForm"
					status-icon
					label-width="100px"
					size="mini"
					:inline="true"
				>
					<el-form-item label="订单序列号" prop="orderNum" class="form-item">
						<el-input
							v-model.trim="searchForm.orderNum"
							placeholder="请输入订单序列号"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="接收人电话" prop="receivePhone" class="form-item">
						<el-input
							v-model.trim="searchForm.receivePhone"
							placeholder="请输入接收者电话"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="发送人电话" prop="senderPhone" class="form-item">
						<el-input
							v-model.trim="searchForm.senderPhone"
							placeholder="请输入发送人电话"
							class="form-input"
						></el-input>
					</el-form-item>
					<el-form-item label="创建时间" prop="createTimes" class="form-item">
						<el-date-picker
							v-model="searchForm.createTimes"
							type="daterange"
							range-separator="-"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="yyyy-MM-dd HH:mm:ss"
							class="form-input"
						>
						</el-date-picker>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>

		<el-row style="padding-bottom: 20px">
			<el-col :push="1" :span="23">
				<el-button type="primary" size="mini" icon="el-icon-search" @click="search"
					>搜索</el-button
				>
				<el-button size="mini" icon="el-icon-refresh" @click="resetForm('searchForm')"
					>重置
				</el-button>
			</el-col>
		</el-row>

		<el-row>
			<el-col :push="1" :span="20">
				<el-button plain type="primary" size="mini" icon="el-icon-plus" @click="create"
					>新增
				</el-button>
				<el-button
					size="mini"
					plain
					type="success"
					icon="el-icon-scissors"
					@click="update"
					:disabled="checkIds.length != 1"
					>修改
				</el-button>
				<el-button
					size="mini"
					plain
					type="danger"
					icon="el-icon-delete-solid"
					@click="remove"
					:disabled="checkIds.length == 0"
					>删除
				</el-button>
			</el-col>

			<el-col :push="1" :span="3">
				<el-tooltip effect="dark" content="隐藏搜索" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-search"
						@click="showSearch = !showSearch"
					>
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="刷新" placement="top">
					<el-button size="mini" circle icon="el-icon-refresh" @click="refresh">
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="用户查询" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-refresh"
						@click="showSearchUserDrawer = true"
					>
					</el-button>
				</el-tooltip>
				<el-tooltip effect="dark" content="隐藏列" placement="top">
					<el-button
						size="mini"
						circle
						icon="el-icon-menu"
						@click="showHidCol = !showHidCol"
					>
					</el-button>
				</el-tooltip>
				<el-popover width="60" placement="bottom" trigger="click" v-model="showHidCol">
					<el-checkbox-group v-model="checkedColumns">
						<el-checkbox v-for="column in columns" :label="column" :key="column">
						</el-checkbox>
					</el-checkbox-group>
				</el-popover>
			</el-col>
		</el-row>

		<el-row>
			<el-table
				ref="multipleTable"
				:data="list"
				tooltip-effect="dark"
				style="width: 100%"
				@selection-change="handMulSelect"
			>
				<el-table-column type="selection"> </el-table-column>
				<el-table-column type="expand" fixed>
					<template slot-scope="scope">
						<el-descriptions direction="vertical" :column="3" border size="small">
							<el-descriptions-item label="商品名称">{{
								scope.row.goodsName
							}}</el-descriptions-item>
							<el-descriptions-item label="发送人姓名">{{
								scope.row.senderName
							}}</el-descriptions-item>
							<el-descriptions-item label="发送人电话">{{
								scope.row.senderPhone
							}}</el-descriptions-item>
							<el-descriptions-item label="发送人地址">{{
								scope.row.senderAddress
							}}</el-descriptions-item>
							<el-descriptions-item label="接收人姓名">{{
								scope.row.receiverName
							}}</el-descriptions-item>
							<el-descriptions-item label="接收人电话">{{
								scope.row.receiverPhone
							}}</el-descriptions-item>
							<el-descriptions-item label="接收人地址">{{
								scope.row.receiverAddress
							}}</el-descriptions-item>
							<el-descriptions-item label="退款状态">
								<el-tag
									effect="dark"
									size="small"
									:type="commColor[scope.row.refund]"
									>{{ scope.row.refund == "0" ? "未退款" : "退款" }}</el-tag
								>
							</el-descriptions-item>
							<el-descriptions-item label="取消状态">
								<el-tag
									effect="dark"
									size="small"
									:type="commColor[scope.row.refund]"
									>{{ scope.row.cancel == "0" ? "未取消" : "取消" }}</el-tag
								>
							</el-descriptions-item>
						</el-descriptions>
					</template>
				</el-table-column>
				<el-table-column
					prop="orderId"
					label="订单编号"
					v-if="$Tool.findEle('订单编号', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					show-overflow-tooltip
					prop="orderNum"
					label="订单序列号"
					v-if="$Tool.findEle('订单序列号', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="totalPrice"
					label="总价格"
					v-if="$Tool.findEle('总价格', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="amount"
					label="交易数量"
					v-if="$Tool.findEle('交易数量', checkedColumns)"
				>
				</el-table-column>
				<el-table-column
					prop="status"
					label="状态"
					v-if="$Tool.findEle('状态', checkedColumns)"
				>
					<template slot-scope="scope">
						<el-tag effect="dark" :type="orderColor[scope.row.status]">
							{{ statusVal[scope.row.status] }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-row v-if="scope.row.orderId != 1">
							<el-button
								@click.native.prevent="updateOne(scope.row)"
								type="text"
								icon="el-icon-scissors"
								size="small"
							>
								修改
							</el-button>
							<el-button
								@click.native.prevent="removeOne(scope.row.orderId)"
								type="text"
								icon="el-icon-delete-solid"
								size="small"
							>
								删除
							</el-button>
							<el-popover placement="bottom" width="80" trigger="hover">
								<el-button
									type="text"
									icon="el-icon-search"
									size="small"
									@click="updateStatus(scope.row)"
								>
									修改订单状态
								</el-button>

								<el-button
									slot="reference"
									type="text"
									icon="el-icon-d-arrow-right"
									size="small"
								>
									更多
								</el-button>
							</el-popover>
						</el-row>
					</template>
				</el-table-column>
			</el-table>
		</el-row>

		<el-row type="flex" justify="center" style="padding-top: 20px">
			<el-col :span="6">
				<el-pagination
					background
					@size-change="handlePageSize"
					@current-change="handlePage"
					:current-page="searchForm.page"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="searchForm.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="listTotal"
				>
				</el-pagination>
			</el-col>
		</el-row>

		<el-dialog
			:title="dialogTitle"
			:visible.sync="showDialog"
			:before-close="closeDialog"
			width="45%"
		>
			<el-form
				:model="submitForm"
				:rules="submitRules"
				ref="submitForm"
				label-width="6.25rem"
				inline
				class="submit-form"
			>
				<el-form-item
					v-if="dialogTitle == '新增订单'"
					label="农产品编号"
					prop="goodsId"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.goodsId"
						placeholder="农产品编号"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '新增订单' && $store.state.user.admin"
					label="商家编号"
					prop="shopId"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.shopId"
						placeholder="商家编号"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '新增订单'"
					label="用户编号"
					prop="buyerId"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.buyerId"
						placeholder="用户编号"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '新增订单'"
					label="产品单价"
					prop="price"
					required
					class="form-item"
				>
					<el-input-number
						clearable
						v-model="submitForm.price"
						placeholder="产品单价"
						:precision="2"
						:step="0.1"
						:min="1"
					></el-input-number>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '新增订单'"
					label="产品总价"
					prop="totalPrice"
					required
					class="form-item"
				>
					<el-input
						disabled
						v-model="submitForm.totalPrice"
						placeholder="产品总价"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '新增订单'"
					label="交易数量"
					prop="amount"
					required
					class="form-item"
				>
					<el-input-number
						clearable
						v-model="submitForm.amount"
						placeholder="交易数量"
						:step="10"
						:min="1"
					></el-input-number>
				</el-form-item>
				<el-form-item label="接收人姓名" prop="receiverName" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.receiverName"
						placeholder="请输入接收人姓名"
					></el-input>
				</el-form-item>
				<el-form-item label="接收人电话" prop="receiverPhone" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.receiverPhone"
						placeholder="请输入接收人手机号码"
					></el-input>
				</el-form-item>
				<el-form-item label="接收人地址" prop="receiverAddress" required class="form-item">
					<el-input
						clearable
						v-model="submitForm.receiverAddress"
						placeholder="请输入接收人地址"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '修改订单'"
					label="发送人姓名"
					prop="senderName"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.senderName"
						placeholder="请输入发送人姓名"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '修改订单'"
					label="发送人电话"
					prop="senderPhone"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.senderPhone"
						placeholder="请输入发送人电话"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '修改订单'"
					label="发送人地址"
					prop="senderAddress"
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.senderAddress"
						placeholder="请输入发送人地址"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '修改订单'"
					label="快递单号"
					prop="expressNum"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.expressNum"
						placeholder="请输入快递单号"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogTitle == '修改订单'"
					label="快递名称"
					prop="expressName"
					required
					class="form-item"
				>
					<el-input
						clearable
						v-model="submitForm.expressName"
						placeholder="请输入快递名称"
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeDialog">取 消</el-button>
				<el-button type="primary" @click="submit(dialogTitle)">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog title="修改订单状态" :visible.sync="showStatusDialog">
			<el-form :model="statusForm" inline>
				<el-form-item label="订单状态" prop="status" class="form-item">
					<el-select v-model="statusForm.status" placeholder="订单状态" clearable>
						<el-option
							v-for="item in statusOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
							class="form-input"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="退款状态" prop="refund" class="form-item">
					<el-select v-model="statusForm.refund" placeholder="退款状态" clearable>
						<el-option
							v-for="item in refundOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
							class="form-input"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="取消状态" prop="cancel" class="form-item">
					<el-select v-model="statusForm.cancel" placeholder="取消状态" clearable>
						<el-option
							v-for="item in cancelOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
							class="form-input"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="form-item form-item-cen">
					<el-button type="primary" @click="submitStatus(0)">修改订单状态</el-button>
					<el-button type="primary" @click="submitStatus(2)">修改退款状态</el-button>
					<el-button type="primary" @click="submitStatus(1)">修改取消状态</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<el-drawer title="用户查询" :visible.sync="showSearchUserDrawer" direction="rtl">
			<el-row style="padding: 10px">
				<el-col>
					<el-input
						placeholder="请输入用户手机号"
						v-model="searchUserPhone"
						class="input-with-select"
					>
						<el-button
							slot="append"
							icon="el-icon-search"
							@click.native="searchUserInfo"
						></el-button>
					</el-input>
				</el-col>
			</el-row>
			<el-row style="padding: 10px">
				<el-empty v-if="!searchUser.username" :image-size="200"></el-empty>
				<el-descriptions
					v-else
					:title="`用户:${searchUser.username}`"
					direction="vertical"
					:column="1"
					border
				>
					<el-descriptions-item label="用户编号">{{
						searchUser.userId
					}}</el-descriptions-item>
					<el-descriptions-item label="用户名">{{
						searchUser.username
					}}</el-descriptions-item>
					<el-descriptions-item label="手机号">{{
						searchUser.phone
					}}</el-descriptions-item>
				</el-descriptions>
			</el-row>
		</el-drawer>
	</div>
</template>

<script>
import { submitRules } from "@/utils/rules/order"
import { commColor } from "@/api/data"
import {
	getAllOrder,
	removeOrder,
	updateOrder,
	createOrder,
	updateOrderStatus,
	updateOrderRefund,
	updateOrderCancel,
} from "@/api/system/order"
import { getOneUserByPhone } from "@/api/system/user"
import {
	columns,
	statusOptions,
	cancelOptions,
	refundOptions,
	statusVal,
	cancelVal,
	refundVal,
	orderColor,
} from "@/constants/order"
export default {
	name: "FrontOrder",
	data() {
		return {
			searchUserPhone: "",
			searchUser: {
				username: "",
				phone: "",
				userId: "",
			},
			showSearchUserDrawer: false,

			showStatusDialog: false,

			showDialog: false,
			dialogTitle: "",

			checkedColumns: columns,
			columns: columns,
			showHidCol: false,
			showSearch: true,
			searchForm: {
				receivePhone: "",
				senderPhone: "",
				orderNum: "",
				createTimes: [],
				page: 1,
				pageSize: 10,
			},
			statusForm: {
				status: "",
				cancel: "",
				refund: "",
			},
			statusOptions: statusOptions,
			refundOptions: refundOptions,
			cancelOptions: cancelOptions,
			statusVal: statusVal,
			orderColor: orderColor,
			commColor: commColor,
			list: [
				{
					orderId: 2,
					orderNum: "123123123",
					totalPrice: 200.0,
					amount: 200,
				},
			],
			listTotal: 0,

			checkIds: [],
			checkedItems: [],

			submitForm: {
				shopId: "",
				buyerId: "",
				goodsId: "",
				amount: 1,
				price: 1,
				totalPrice: 1,
				senderName: "",
				senderAddress: "",
				senderPhone: "",
				receiverName: "",
				receiverAddress: "",
				receiverPhone: "",
				expressName: "",
				expressNum: "",
			},
		}
	},
	computed: {
		submitRules,
	},
	watch: {
		"submitForm.amount": {
			handler() {
				let { amount, price } = this.submitForm
				this.submitForm.totalPrice = this.$Tool.retainTwo(amount * price)
			},
		},
		"submitForm.price": {
			handler() {
				let { amount, price } = this.submitForm
				this.submitForm.totalPrice = this.$Tool.retainTwo(amount * price)
			},
		},
	},

	mounted() {
		this.get()
	},

	methods: {
		async searchUserInfo() {
			let phone = this.searchUserPhone
			let res = await getOneUserByPhone({ phone })
			if (res.code == 200 && res.data) {
				this.searchUser = res.data
			}
		},
		search() {
			this.get()
		},
		create() {
			this.openDialog("新增订单")
		},
		update() {
			this.openDialog("修改订单")
			this.$nextTick(() => {
				this.submitForm = { ...this.checkedItems[0], price: 1 }
			})
		},
		async get() {
			let search = { ...this.searchForm }
			if (search.createTimes.length !== 0) {
				search.beginTime = search.createTimes[0]
				search.endTime = search.createTimes[1]
				delete search.createTimes
			}
			let res = await getAllOrder(this.$Tool.removeNullFiled(search))
			if (res.code == 200) {
				this.list = res.data
				this.listTotal = res.total
			}
		},

		openDialog(title) {
			this.showDialog = true
			this.dialogTitle = title
		},

		closeDialog() {
			this.resetForm("submitForm")
			this.showDialog = false
			this.dialogTitle = ""
		},

		async submit(title) {
			if (this.checkForm(this, "submitForm")) {
				if (title == "新增订单") {
					this.submitCreate(title)
				} else if (title == "修改订单") {
					this.submitUpdate(title)
				}
			}
		},

		updateStatus(item) {
			this.showStatusDialog = true
			this.statusForm = {
				orderId: item.orderId,
				status: item.status,
				cancel: item.cancel,
				refund: item.refund,
			}
		},
		submitStatus(flag) {
			let { orderId, cancel, status, refund } = this.statusForm
			if (flag == 0) {
				this.handConfirmStatus("", orderId, statusVal[status], this.submitOrderStatus)
			} else if (flag == 1) {
				this.handConfirmStatus("取消", orderId, cancelVal[cancel], this.submitOrderCancel)
			} else if (flag == 2) {
				this.handConfirmStatus("取消", orderId, refundVal[refund], this.submitOrderRefund)
			}
		},
		async submitOrderStatus() {
			let { orderId, status } = this.statusForm
			let res = await updateOrderStatus({ orderId, status })
			if (res.code == 200) {
				this.sucMes(this, "修改订单状态成功")
				this.refresh()
			}
		},
		async submitOrderCancel() {
			let { orderId, cancel } = this.statusForm
			let res = await updateOrderCancel({ orderId, cancel })
			if (res.code == 200) {
				this.sucMes(this, "修改取消状态成功")
				this.refresh()
			}
		},
		async submitOrderRefund() {
			let { orderId, refund } = this.statusForm
			let res = await updateOrderRefund({ orderId, refund })
			if (res.code == 200) {
				this.sucMes(this, "修改退款状态成功")
				this.refresh()
			}
		},
		handConfirmStatus(text, data1, data2, success, error = () => {}) {
			this.confirm(
				this.$confirm,
				`您是否确认修改订单编号为"${this.$Tool.handlerLongStr(
					data1.toString()
				)}"的数据项,订单${text}状态为${data2}`,
				success,
				error
			)
		},
		async submitUpdate(title) {
			let res = await updateOrder(this.submitForm)
			if (res.code == 200) {
				this.refresh()
				this.closeDialog()
			} else {
				this.openDialog(title)
			}
		},
		async submitCreate(title) {
			let res = await createOrder(this.submitForm)
			if (res.code == 200) {
				this.refresh()
				this.closeDialog()
			} else {
				this.openDialog(title)
			}
		},
		remove() {
			let orderIds = this.checkIds
			this.handConfirm("删除", orderIds, async () => {
				let res = await removeOrder({ orderIds })
				if (res.code == 200) {
					this.refresh()
				}
			})
		},
		refresh() {
			this.get()
		},
		updateOne(item) {
			this.submitForm = { ...item }
			this.openDialog("修改订单")
		},
		removeOne(orderId) {
			this.handConfirm("删除", orderId, async () => {
				let orderIds = [orderId]
				let res = await removeOrder({ orderIds })
				if (res.code == 200) {
					this.refresh()
				}
			})
		},
		resetForm(formName) {
			this.$Tool.objEmptyStr(this[formName], "page", "pageSize")
			this.$refs[formName].resetFields()
		},

		handMulSelect(list) {
			this.checkIds = list.map((item) => item.orderId)
			this.checkedItems = list
		},
		handlePageSize(val) {
			this.searchForm.pageSize = val
			this.refresh()
		},
		handlePage(val) {
			this.searchForm.page = val
			this.refresh()
		},

		handConfirm(text, data, success, error = () => {}) {
			this.confirm(
				this.$confirm,
				`您是否确认${text}订单编号为"${this.$Tool.handlerLongStr(
					data.toString()
				)}"的数据项`,
				success,
				error
			)
		},
	},
}
</script>

<style lang="scss" scoped></style>
